package com.danco.training.controller;

import java.io.FileWriter;
import java.io.IOException;




import java.io.Serializable;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.danco.training.bookshop.entity.Book;
import com.danco.training.bookshop.entity.Order;
import com.danco.training.bookshop.entity.storage.BookStorage;
import com.danco.training.bookshop.entity.storage.Bookshop;
import com.danco.training.bookshop.service.file.BookStorageFile;
import com.danco.training.bookshop.service.storage.BookStorageService;
import com.danco.training.csvworker.CSVReader;
import com.danco.training.view.IOUtil;
import com.danco.training.view.Separator;

public class BookController implements Serializable {


	/**
	 * 
	 */
	private static final long serialVersionUID = -7756135075913910871L;
	private BookStorageService bookStorageService = Bookshop.getBookshopInstance().getBookStorageService();
	
	

	public void printBookList() {
		IOUtil.write("Books in Bookstorage");
		for (Book book: bookStorageService.getBookList()){
			IOUtil.write(bookDetails(book.getId()));
		}
		

	}

	public void printBookListSortedByAlphabet() {
		IOUtil.write("Books in Bookstorage sorted by alphabet");
		for (Book book: bookStorageService.sortBooksByAlphabet(bookStorageService.getBookList())){
			IOUtil.write(bookDetails(book.getId()));
		}
		
	}

	public void printBookListSortedByPublicationDate() {
		IOUtil.write("Books in Bookstorage sorted by publication date");
		for (Book book: bookStorageService.sortBooksByPublicationDate(bookStorageService.getBookList())){
			IOUtil.write(bookDetails(book.getId()));
		}
		
		
	}

	public void printBookListSortedByPrice() {
		IOUtil.write("Books in Bookstorage sorted by price");
		for (Book book: bookStorageService.sortBooksByPrice(bookStorageService.getBookList())){
			IOUtil.write(bookDetails(book.getId()));
		}
	}

	public void printAvailableBooks(){
		IOUtil.write("Available Books in Bookstorage ");
		for (Book book: bookStorageService.getAvailableBooks()){
			IOUtil.write(bookDetails(book.getId()));
		}
		
}

	public void printNotAvailableBooks() {
		IOUtil.write("Not available Books in Bookstorage ");
		for (Book book: bookStorageService.getNotAvailableBooks()){
			IOUtil.write(bookDetails(book.getId()));
		}
	}

	public void printUnsoldBooksSortedByReceiptDate() {
		IOUtil.write("Books in Bookstorage unsold for some months sorted by receipt date");
		for (Book book:bookStorageService.sortUnsoldBooksByReceiptDate(bookStorageService.getBookList())){
			IOUtil.write(bookDetails(book.getId()));
		}
	

	}

	public void printUnsoldBooksSortedByPrice() {
		IOUtil.write("Unsold Books in Bookstorage  sorted by price");
		for (Book book: bookStorageService.sortUnsoldBooksByPrice(bookStorageService.getBookList())){
			IOUtil.write(bookDetails(book.getId()));
		}
		

	}

	public void createBook()  {
		IOUtil.write("Book creation");
		
		IOUtil.write("Enter bookTitle:");
		String title = IOUtil.read();
		IOUtil.write("Enter bookAuthor:");
		String author = IOUtil.read();
		IOUtil.write("Enter publication date yyyy-[m]m-[d]d:");
		Date date = IOUtil.readDate();
		Book book = new Book(bookStorageService.generateUnexistedId(),title,author,date);
		bookStorageService.addBook(book);
		IOUtil.write("Book is created");
		IOUtil.write(bookDetails(book.getId()));
		
		

	}
	
	public String bookDetails(int index){
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd");
		
		
		
		Book book = bookStorageService.getBookById(index);
		StringBuffer str = new StringBuffer();
		
		str.append(book.getId());
		str.append(Separator.SEPARATOR.getS());		
		str.append(book.getTitle());
		str.append(Separator.SEPARATOR.getS());
		str.append(book.getAuthor());
		str.append(Separator.SEPARATOR.getS());
		str.append(sdf.format(book.getPublicationDate()));
		
		return str.toString();
	}

	

	public void printBookInfo() {
		
		IOUtil.write("Enter book's to show Id");
		int id = IOUtil.readInt();
		while (bookStorageService.getBookById(id)== null){
			IOUtil.write("Book not existed");
			IOUtil.write("Enter book's to show Id");
			id = IOUtil.readInt();
			
		}
		IOUtil.write("Book details");
		IOUtil.write(bookDetails(id));
		

	}

	public void updateBook()  {
		IOUtil.write("Book modifying");
		IOUtil.write("Enter book Id: ");
		int id = IOUtil.readInt(); 
		while (bookStorageService.getBookById(id)== null){
			IOUtil.write("Book not existed");
			IOUtil.write("Enter book Id");
			id = IOUtil.readInt();
		}
		Book book = bookStorageService.getBookById(id);
		IOUtil.write("Enter new title:");
		String t = IOUtil.read();
		if (!t.isEmpty()){
			book.setTitle(t);
		}
		IOUtil.write("Enter new author:");
		if (!IOUtil.read().isEmpty()){
			book.setAuthor(IOUtil.read());
		}
		IOUtil.write("Enter new publication date yyyy-[m]m-[d]d:");
		if (!IOUtil.read().isEmpty()){
			book.setPublicationDate(IOUtil.readDate());
		}
		IOUtil.write("Enter new price:");
		if (!IOUtil.read().isEmpty()){
			book.setPrice(IOUtil.readDouble());
		}
		IOUtil.write("Enter new quantity:");
		if (!IOUtil.read().isEmpty()){
			book.setQuantity(IOUtil.readInt());
		}
		IOUtil.write("Enter new receipt date yyyy-[m]m-[d]d:");
		if (!IOUtil.read().isEmpty()){
			book.setReceiptDate(IOUtil.readDate());
		}
		
		IOUtil.write("Book is modified");
		IOUtil.write(bookDetails(id));
		

	}

	public void deleteBook() {
		IOUtil.write("Book deleting");
		IOUtil.write("Enter bookId:");
		int id = IOUtil.readInt();
		while (bookStorageService.getBookById(id)== null){
			IOUtil.write("Book not existed");
			IOUtil.write("Enter another Id");
			id = IOUtil.readInt();
		}
		bookStorageService.removeBookById(id);

	}

	public void saveBookListToFile() throws IOException {
		
		IOUtil.write("Enter directory and file name :");
		String file = IOUtil.read();
		if (file.isEmpty()){
			file = "d:\\file3.csv";
			IOUtil.write("Saved by default in ");
			
		}
		try
		{
		FileWriter writer = new FileWriter(file,false);
		for(int id: bookStorageService.getBookListId()){
			if(CSVReader.existedEntity(file, id)){
				writer.append('\n');
			}
			else{
			writer.append(bookDetails(id));
			writer.append('\n');
			}
		}
	        writer.close();
	    }
	    catch(IOException e)
	    {
	         e.printStackTrace();
	    }

	}
	
public void readBookListFromFile() throws IOException {
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd");
	Date date = new Date();
	
	    
		IOUtil.write("Enter directory and file name :");
		String file = IOUtil.read();
		if (file.isEmpty()){
			file = "d:\\file3.csv";
			IOUtil.write("Saved by default in d:\file3.csv");
			
			
		}
		for (int i = 0; i < CSVReader.readFile(file).length; i++) {
			String book[] = CSVReader.readFile(file)[i].split(Separator.SEPARATOR.getS());
			try {
				date = sdf.parse(book[3]);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Book b = new Book(Integer.parseInt(book[0]),book[1], book[2],date);
			bookStorageService.addBook(b);
		    
		}

	}

}
